package com.cskaoyan.gateway.controller.promotion;

import com.mall.commons.result.ResponseData;
import com.mall.commons.result.ResponseUtil;
import com.mall.commons.tool.utils.GetUserInfoUtil;
import com.mall.promo.PromoService;
import com.mall.promo.dto.*;
import com.mall.user.annotation.Anoymous;
import com.mall.user.constants.SysRetCodeConstants;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Author  kkw
 * Date  2021/6/24 21:46
 * Version 1.0
 * Description :
 */
@Slf4j
@RestController
@RequestMapping("shopping")
public class PromotionController {

    @Reference(check = false)
    PromoService promoService;

    @GetMapping("seckilllist")
    @Anoymous
    public ResponseData getSecKillList(Integer sessionId) {
        PromoInfoRequest request = new PromoInfoRequest();
        SimpleDateFormat yyyyMMdd = new SimpleDateFormat("yyyyMMdd");
        String formatDate = yyyyMMdd.format(new Date());

        request.setSessionId(sessionId);
        request.setYyyymmdd(formatDate);

        PromoInfoResponse response = promoService.getPromoList(request);
        if (SysRetCodeConstants.SUCCESS.getCode().equals(response.getCode())) {
            return new ResponseUtil<>().setData(response);
        }
        return new ResponseUtil<>().setErrorMsg(response.getMsg());
    }


    @PostMapping("promoProductDetail")
    public ResponseData getDetails(@RequestBody PromoProductDetailRequest request) {
        PromoProductDetailResponse response = promoService.getPromoProductDetail(request);
        if (SysRetCodeConstants.SUCCESS.getCode().equals(response.getCode())) {
            return new ResponseUtil<>().setData(response);
        }
        return new ResponseUtil<>().setErrorMsg(response.getMsg());
    }

    @PostMapping("seckill")
    public ResponseData createsSecKill(@RequestBody CreatePromoOrderRequest request, HttpServletRequest res) {
        Long uid = GetUserInfoUtil.getUid(res);
        request.setUserId(uid);
        //非分布式下单接口
//        CreatePromoOrderResponse response = promoService.createPromoOrder(request);
        //分布式事务的下单接口
        CreatePromoOrderResponse response = promoService.createPromoOrderInTransaction(request);
        if (SysRetCodeConstants.SUCCESS.getCode().equals(response.getCode())) {
            return new ResponseUtil<>().setData(response);
        }
        return new ResponseUtil<>().setErrorMsg(response.getMsg());
    }
}
